package models;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import play.db.jpa.Model;

@Entity
@Table(name = "types")
public class Types extends Model {

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "company_id")
	public Company company;
	@Column(name = "name")
	public String name;
	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "types")
	public Set<Product> products = new HashSet<Product>(0);
	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "types")
	public Set<Trade> trades = new HashSet<Trade>(0);

	public Types() {
	}

	public Types(Company company, String name, Set<Product> products, Set<Trade> trades) {
		this.company = company;
		this.name = name;
		this.products = products;
		this.trades = trades;
	}
	
	
	
	/**
	 * 取出售信息最高的topSize个分类
	 * @param topSize
	 * @return
	 */
	public static  List<Types> getTopSaleTypes(int topSize){
		
		String hql=" select product.types from Sale sale " +
				   "inner join  sale.product product " +
				   "inner join product.types types " +
				   "group by (types) order by count(types) desc  " ;
		
		List<Types> fetch = find(hql).fetch(topSize);
		return fetch;
	}
	
	/**
	 * 取求购信息最高的topSize个分类
	 * @param topSize
	 * @return
	 */
	public static  List<Types> getTopTradeTypes(int topSize){
		
		String hql="select types from Trade trade " +
					"inner join trade.tradeproductlists trlist " +
					"inner join trlist.product product " +
					"inner join product.types types " +
					"group by types order by count(types) desc";
		
		return find(hql).fetch(topSize);
	}
	
	

}